<?php

namespace app\store\controller\spike;

use app\store\controller\BaseController;
use app\store\model\SpikeSession;
use app\store\service\SpikeSessionService;
use think\facade\Db;
use think\facade\View;

class SessionController extends BaseController
{
    public function index()
    {   
        $id = $this->request->param('id');
        $SpikeSessionService = new SpikeSessionService();

        $list = $SpikeSessionService->getSpikeSessionList($id);

        if(!$this->request->isPjax()){
            View::engine()->layout(true);
        }

        return View::fetch('',['list' => $list]);
    }

    public function goods()
    {
        $spike_session_id = $this->request->param('spike_session_id');
        $spikeSessionService = new SpikeSessionService();

        $list = $spikeSessionService->getSpikeSessionGoods($spike_session_id);

        $ids = [];

        if(!$list->isEmpty()){
            $data = $list->toArray()['data'];
            $ids  = array_column($data,'spike_goods_id');

        }

        return View::fetch('',['spike_session_id' => $spike_session_id,'ids' => json_encode($ids),'list' => $list]);
    
    }

    public function saveGoods()
    {   
        $param = $this->request->param('session_goods');

        $res  = SpikeSessionService::saveSpikeSessionGoods($param);

        return $res ? json(['code' => 1,'msg' => '添加成功!']) : json(['code' => 0, 'msg' => '添加失败']);
    }
    
    /**
     *
     * 删除会场及商品信息
     * */
    public function delete()
    {
        $id = $this->request->get('id/d');
        Db::startTrans();
        try {
            Db::name('spike_session')->where('id',$id)->delete();
            Db::name('spike_session_goods')->where('spike_session_id',$id)->delete();
            // 提交事务
            Db::commit();

            return  json(['code' => 1,'msg' => '删除成功!']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();

            return  json(['code' => 0, 'msg' => '删除失败']);
        }
    }

    // 删除该场次的商品
    public function deleteGoods()
    {
        $id = $this->request->get('id/d');

        $res = SpikeSessionService::deleteSpikeSessionGoods($id);

        return  $res ? json(['code' => 1,'msg' => '删除成功!']) : json(['code' => 0, 'msg' => '删除失败']);

    }
}